package com.xz.cstone.data;

import java.util.ArrayList;
import java.util.List;

public class TreeSet {
	
	private List<CElement> elements = new ArrayList<CElement>();
	private int[] p = new int[0];
	private int[] rank = new int[0];
	
	public TreeSet(ClusterData data) {
		this.elements = data.elements;
		this.p = new int[elements.size()];
		this.rank = new int[elements.size()];
		
		for (int i = 0; i < elements.size(); i++) {
			makeSet(i);
		}
	}
	
	public void makeSet(int x) {
		p[x] = x;
		rank[x] = 0;
	}
	
	public void union(int x, int y) {
		link(findSet(x), findSet(y));
	}
	
	public void link(int x, int y) {
		if (findSet(x) == findSet(y)) {
			return;
		}
		if (rank[x] > rank[y]) {
			p[y] = x;
		} else if (rank[x] < rank[y]) {
			p[x] = y;
		} else {
			rank[x]++;
			p[y] = x;
		}
	}
	
	public int findSet(int x) {
		if (p[x] != x) {
			p[x] = findSet(p[x]);
		}
		return p[x];
	}
}
